﻿using ProTrack.Entity;
using ProTrack.IRepository;
using ProTrack.IServices.StoreHouse;
using ProTrack.IServices.Works;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace ProTrack.Services.StoreHouse
{
    public class WarehouseServices : IWarehouseServices
    {
        public WarehouseServices(IBaseRepository db)
        {
            Db = db;
        }
        public IBaseRepository Db { get; }
        public async Task<bool> AddAsync(Warehouse model)
        {
            var result = await Db.InsertAsync(model);
            return result;
        }

        public async Task<bool> DeleteAsync(int[] Ids)
        {
            string sql = "delete Warehouse where Id in @Ids";
            var result = await Db.DeleteAsync(sql, new { Ids });
            return result;
        }

        public async Task<bool> DeleteAsync(int Id)
        {
            string sql = "delete Warehouse where Id = @Id";
            var result = await Db.DeleteAsync(sql, new { Id });
            return result;
        }

        public async Task<IEnumerable<Warehouse>> GetAllAsync()
        {
            string sql = "select * from Warehouse ";
            var list = await Db.QueryAllAsync<Warehouse>(sql);
            return list;
        }

        public async Task<IEnumerable<Warehouse>> GetAsync(int PageIndex, int PageSize, string WarehouseNumber, string WarehouseName)
        {
            string sql = "select * from Warehouse where 1=1";
            if (!string.IsNullOrEmpty(WarehouseNumber))
            {
                sql += "and WarehouseNumber like @WarehouseNumber";
            }
            if (!string.IsNullOrEmpty(WarehouseName))
            {
                sql += "and WarehouseName like @WarehouseName";
            }
            sql += " order by CreateTime desc offset @PageSize*(@PageIndex-1) row fetch next @PageSize rows only ";
            var list = await Db.QueryAsync<Warehouse>(sql, new { PageIndex, PageSize, WarehouseNumber = $"%{WarehouseNumber}%", WarehouseName = $"%{WarehouseName}%" });
            return list;
        }

        public async Task<int> GetCountAsync(string WarehouseNumber, string WarehouseName)
        {
            string sql = "select count(*) from Warehouse where 1=1";
            if (!string.IsNullOrEmpty(WarehouseNumber))
            {
                sql += " and WarehouseNumber like @WarehouseNumber ";
            }
            if (!string.IsNullOrEmpty(WarehouseName))
            {
                sql += " and WarehouseName like @WarehouseName ";
            }
            var list = await Db.GetRecoreCountAsync(sql, new { WarehouseNumber = $"%{WarehouseNumber}%", WarehouseName = $"%{WarehouseName}%" });
            return list;
        }

        public async Task<bool> UpdateAsync(Warehouse model)
        {
            var result = await Db.UpdateAsync(model);
            return result;
        }
    }
}
